import { Component, ViewChild, OnInit, DoCheck } from '@angular/core';
import { NavParams, Events, AlertController, App, ModalController, NavController, Content, ActionSheetController, LoadingController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { Config } from '../../../../providers/config';
import { DomSanitizer } from '@angular/platform-browser';
import _ from 'lodash';
import * as moment from "moment";

import { Common } from "../../../../providers/common";
import {IrpSchedulerListervice} from "./list.service";

@Component({
  selector: 'page-irp-scheduler-list',
  templateUrl: './list.html',
  providers: [IrpSchedulerListervice]
})
export class IrpSchedulerListPage implements OnInit{
	moa_page_name: any = "page-irp-scheduler-list";
  moa_page_explain: any = "日程管理";

  @ViewChild("calendar")
  calendar: any;
  @ViewChild("DatetimePicker")
  DatetimePicker: any;

  showCalendar = true;

  wHeads = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];

  selectedDay = new Date("2017-11-10");

  showAllInfo = false;

  nextMonth: any = null;
  preMonth: any = null;

  returnData = null;
  listData = [];
  pageIndex = 1;
  isLoadMore = true;
  selectedDateTime = "";

  constructor(
    public alertCtrl: AlertController,
    public app: App,
    public modalCtrl: ModalController,
    public navCtrl: NavController,
    public config: Config,
    private sanitizer: DomSanitizer,
    public events: Events,
    public storage: Storage,
    private common: Common,
    private actionSheetCtrl: ActionSheetController,
    private navParams: NavParams,
    public loadingCtrl: LoadingController,
    private listService: IrpSchedulerListervice
  ) {

  }

  ngOnInit() {
    this.calendar.wHeads = this.wHeads;

    // delete this.calendar.month[this.calendar.month.length - 1];
  }

  ngDoCheck() {
    // this.calendar.ngOnChanges();
  }

  onSelectedDate(e) {
    this.setListData(e.selectedDate.day);
  }

  ionViewDidEnter() {

    console.log("DatetimePicker>>>>>>>>", this.DatetimePicker);

    console.log("Calendar.ionViewDidEnter()>>>>>>>>>>", this.calendar);
    let scheduler = document.getElementById("scheduler");
    if (scheduler) {
      let calendar_header = scheduler.getElementsByClassName("calendar-header")[0];
      let leftDiv = calendar_header.getElementsByClassName("left")[0];
      let rightDiv = calendar_header.getElementsByClassName("right")[0];
      let monthDiv = calendar_header.getElementsByClassName("month")[0];
      leftDiv.addEventListener("click", () => {
        this.changeCalendar();
      });

      monthDiv.addEventListener("click", () => {
        // this.DatetimePicker.open();
      });

      rightDiv.addEventListener("click", () => {
        this.changeCalendar();
      });
    }
    this.changeCalendar();
  }

  changeCalendar() {
    /*if (this.calendar.month[5]) {
      delete this.calendar.month[5];
    }*/
    console.log(">>>>>>>>>>>>>", this.calendar);


    let params = {
      startdate: moment(this.calendar.current).startOf("month").format("YYYY-MM-DD"),
      enddate: moment(this.calendar.current).endOf("month").format("YYYY-MM-DD"),
      pageIndex: this.pageIndex,
      pageSize: this.config.pageSize
    };
    this.listService.getIRMScheduler(params).subscribe(returnData => {
      console.log("getIRMScheduler.returnData>>>>>", returnData);
      this.returnData = returnData;

      if (this.calendar.selectedDay) {
        // this.setListData(this.calendar.selectedDay.day);
      } else {
        if (moment(this.calendar.current).format("YYYY-MM-DD") === moment().format("YYYY-MM-DD")) {
          this.setListData(this.calendar.current);
        }
      }

      this.setViewData();
    });

  }

  setListData(date) {
    let currentDateStr = moment(date).format("YYYY-MM-DD");
    this.listData = _.filter(this.returnData, data => {
      return currentDateStr >= moment(data["startdate"]).format("YYYY-MM-DD")
        && currentDateStr <= moment(data["enddate"]).format("YYYY-MM-DD");
    });

    if (!(this.listData && this.listData.length > 0)) {
      this.isLoadMore = false;
    } else {
      this.isLoadMore = true;

      _.forEach(this.listData, data => {
        data["startdate"] = moment(data["startdate"]).format("YYYY-MM-DD");
        data["enddate"] = moment(data["enddate"]).format("YYYY-MM-DD");
      });
    }
  }

  setViewData() {

    let scheduler = document.getElementById("scheduler");
    if (scheduler) {
      let calendar_weeks = scheduler.getElementsByClassName("calendar-week");
      let calendar_header = scheduler.getElementsByClassName("calendar-header")[0];
      let monthDiv = calendar_header.getElementsByClassName("month")[0];
      monthDiv.innerHTML = moment(this.calendar.current).format("YYYY年 MM月");
      if (calendar_weeks) {
        _.forEach(calendar_weeks, (week, weekIndex) => {
          let calendar_days = week.getElementsByClassName("calendar-day-wrapper");
          if (calendar_days) {
            let diffNum = 0;
            _.forEach(calendar_days, (day, dayIndex) => {
              let dateStr = moment(this.calendar.month[weekIndex][dayIndex]["day"]).format("YYYY-MM-DD");
              let tempList = _.filter(this.returnData, data => {
                return dateStr >= moment(data["startdate"]).format("YYYY-MM-DD")
                  && dateStr <= moment(data["enddate"]).format("YYYY-MM-DD");
              });
              if (tempList && tempList.length > 0) {
                day.className += " hasRecord";

                this.addRecordFlag(day);
              }

              if (this.calendar.selectedDay
                && moment(this.calendar.selectedDay.day).format("YYYY-MM-DD") === dateStr) {
                day.getElementsByClassName("calendar-day")[0].className += " selected";
              }

              if (day.className.indexOf("diff-month") > -1) {
                diffNum++;
              }

              if (this.calendar.month[weekIndex] && diffNum === calendar_days.length) {
                week["style"].display = "none";
              }
            });
          }
        })
      }
    }
  }

  addRecordFlag(day) {
    let cDay = day.getElementsByClassName("calendar-day")[0];
    if (cDay) {
      let flagDiv = document.createElement("div");
      flagDiv.className = "recordFlag";
      let chuchaiDiv = document.createElement("div");
      chuchaiDiv.className = "chuchaiFlag";
      let luyanDiv = document.createElement("div");
      luyanDiv.className = "luyanFlag";
      flagDiv.appendChild(chuchaiDiv);
      flagDiv.appendChild(luyanDiv);
      cDay.appendChild(flagDiv);
    }
  }

  DateTimeChange() {
    console.log(this.selectedDateTime);
    console.log(moment(this.selectedDateTime));
    console.log(new Date(this.selectedDateTime));
    // this.calendar.current = new Date(this.selectedDateTime);
    // this.changeCalendar();
    console.log(this.calendar);
  }

  setShowAllInfo() {
    this.showAllInfo = !this.showAllInfo;
  }

}
